package com.huixiaodian.baselibrary.utils;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import java.util.Objects;

public class UIUtil {

    public static int dipToPx(Context context, int dip) {
        return (int) (dip * getScreenDensity(context) + 0.5f);
    }

    public static int sipToPx(Context context, int spValue) {
        return (int) (spValue * getScreenScaledDensity(context) + 0.5f);
    }

    private static float getScreenDensity(Context context) {
            DisplayMetrics metrics = new DisplayMetrics();
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
                    .getDefaultDisplay().getMetrics(metrics);
            return metrics.density;
    }

    public static int getScreenWidthPixels(Context context){
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(metrics);
        return metrics.widthPixels;
    }

    public static int getScreenHeightPixels(Context context){
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(metrics);
        return metrics.heightPixels;
    }

    private static float getScreenScaledDensity(Context context){
        DisplayMetrics metrics = new DisplayMetrics();
        ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getMetrics(metrics);
        return metrics.scaledDensity;
    }


    public static int getStatusBarHeight(Context context){
        int statusBarHeight = 0;
        try{
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(
                    Objects.requireNonNull(clazz.getField("status_bar_height").get(object)).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(height);
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 显示控件
     * @param view 需要显示的控件
     * @return 需要显示控件的状态 为true时显示控件
     */
    public static boolean isViewVisible(View view){
        return view != null && (view.getVisibility() == View.GONE ||
                view.getVisibility() == View.INVISIBLE);
    }

    /**
     * 显示控件
     * @param view 需要隐藏的控件
     * @return 需要隐藏控件的状态 为true时隐藏控件
     */
    public static boolean isViewHide(View view){
        return view != null && (view.getVisibility() == View.VISIBLE ||
                view.getVisibility() == View.INVISIBLE);
    }
}
